import puppeteer from "../../../lib/puppeteer/puppeteer.js";
import {
    getGroupPlayerList,
    getPlayerData,
    deletePlayerData,
    storagePlayerData,
    PLUGIN_PATH
} from "../function/function.js";

export class Rankings extends plugin {
    constructor() {
        super({
            name: '[Sm]排行榜',
            dsc: '查看奴隶身价和资金排行榜',
            event: 'message',
            priority: 1,
            rule: [
                { reg: /^[#\/]奴隶(身价|资金)排行榜$/, fnc: 'showRankings' }
            ]
        })
    }

    async showRankings(e) {
        try {
            if (!e.isGroup) return e.reply(['该功能只能在群内使用']);
            const ID = [e.user_id, e.group_id];
            const type = e.msg.includes('身价') ? 'value' : 'currency';

            const playerList = getGroupPlayerList(ID[1]);
            const rankings = [];

            const memberInfoList = Object.fromEntries([...await Bot.pickGroup(ID[1]).getMemberMap()]);

            for (const playerId of playerList) {
                let errorQQ = '';
                try {
                    const qq = playerId.replace('.json', '');
                    errorQQ = qq;
                    if (!memberInfoList[qq]) {
                        const playerData = await getPlayerData(ID[1], qq);

                        if (playerData.slave && playerData.slave.length > 0) {
                            for (const slaveQQ of playerData.slave) {
                                const slaveData = await getPlayerData(ID[1], slaveQQ);
                                if (slaveData) {
                                    slaveData.master = '';
                                    storagePlayerData(ID[1], slaveQQ, slaveData);
                                }
                            }
                        }

                        if (playerData.master) {
                            const masterData = await getPlayerData(ID[1], playerData.master);
                            if (masterData) {
                                masterData.slave = masterData.slave.filter(slaveQQ => slaveQQ !== qq);
                                storagePlayerData(ID[1], playerData.master, masterData);
                            }
                        }

                        deletePlayerData(ID[1], qq);
                        continue;
                    }

                    const playerData = await getPlayerData(ID[1], qq);

                    // 使用存储的nickname，如果没有则使用群名片或昵称
                    const nickname = playerData.nickname ||
                        memberInfoList[qq].card ||
                        memberInfoList[qq].nickname;

                    // 更新玩家昵称
                    if (nickname !== playerData.nickname) {
                        storagePlayerData(ID[1], qq, playerData, nickname);
                    }

                    rankings.push({
                        id: qq,
                        value: playerData[type],
                        nickname: nickname
                    });
                } catch (err) {
                    logger.error(`处理玩家数据时出错 [群:${ID[1]}, QQ:${errorQQ}]：`, err);
                    continue;
                }
            }

            rankings.sort((a, b) => b.value - a.value);

            const topRankings = rankings.slice(0, 15);
            const info = topRankings.map((player, index) => ({
                rank: index + 1,
                id: player.id,
                value: player.value,
                nickname: player.nickname
            }));

            const image = await puppeteer.screenshot('排行榜', {
                tplFile: 'plugins/Slave-Market/resources/html/rankings/index.html',
                filePath: `${PLUGIN_PATH}/resources/`,
                info,
                type: type === 'value' ? '身价' : '资金'
            });

            return e.reply([image]);
        } catch (err) {
            logger.error(`生成排行榜时出错 [群:${e.group_id}]：`, err);
            return e.reply(['生成排行榜时发生错误，请稍后再试']);
        }
    }
}
